// 创建axios实例
const apiClient = axios.create({
    timeout: 5000, // 请求超时时间
    headers: {'Content-Type': 'application/json'}
});

// 请求拦截器
apiClient.interceptors.request.use(config => {
    const token = localStorage.getItem('token'); // 从localStorage获取token
    config.headers['token'] = token; // 如果存在token，则添加到header中
    return config;
}, error => {
    return Promise.reject(error);
});

let that = this
// 响应拦截器
apiClient.interceptors.response.use(response => {
    // 处理正常响应
    console.log('axios')
    return response.data;
}, error => {
    if (error.response && error.response.status === 403) {
        // 如果返回的状态码是403，则跳转到登录页
        window.location.href = '/login';
    } else {
        // Message.error('未授权，请先登录');
    }
    return Promise.reject(error);
});

// 封装get请求
function get(url, params) {
    return new Promise((resolve, reject) => {
        apiClient.get(url, {params})
            .then(response => resolve(response))
            .catch(error => reject(error));
    });
}

// 封装post请求
function post(url, data) {
    return new Promise((resolve, reject) => {
        apiClient.post(url, data)
            .then(response => resolve(response))
            .catch(error => reject(error));
    });
}

// 导出函数供外部调用
window.api = {
    get: get,
    post: post
};
